package com.energy.analysis.sys.controller;

import com.energy.analysis.comm.utils.DateUtils;
import com.energy.analysis.sys.entity.OprInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ConcurrentAccessException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    private static Logger log = LoggerFactory.getLogger(LoginController.class);
    
//    shiro异常
//    <!-- 身份认证异常 -->
//    <!-- 身份令牌异常，不支持的身份令牌 -->
//    org.apache.shiro.authc.pam.UnsupportedTokenException
//     
//    <!-- 未知账户/没找到帐号,登录失败 -->
//    org.apache.shiro.authc.UnknownAccountException
//    <!-- 帐号锁定 -->
//    org.apache.shiro.authc.LockedAccountException
//    <!-- 用户禁用 -->
//    org.apache.shiro.authc.DisabledAccountException
//    <!-- 登录重试次数，超限。只允许在一段时间内允许有一定数量的认证尝试 -->
//    org.apache.shiro.authc.ExcessiveAttemptsException
//    <!-- 一个用户多次登录异常：不允许多次登录，只能登录一次 。即不允许多处登录-->
//    org.apache.shiro.authc.ConcurrentAccessException
//    <!-- 账户异常 -->
//    org.apache.shiro.authc.AccountException
//     
//    <!-- 过期的凭据异常 -->
//    org.apache.shiro.authc.ExpiredCredentialsException
//    <!-- 错误的凭据异常 -->
//    org.apache.shiro.authc.IncorrectCredentialsException
//    <!-- 凭据异常 -->
//    org.apache.shiro.authc.CredentialsException
//    org.apache.shiro.authc.AuthenticationException
//     
//    <!-- 权限异常 -->
//    <!-- 没有访问权限，访问异常 -->
//    org.apache.shiro.authz.HostUnauthorizedException
//    org.apache.shiro.authz.UnauthorizedException
//    <!-- 授权异常 -->
//    org.apache.shiro.authz.UnauthenticatedException
//    org.apache.shiro.authz.AuthorizationException
//     
//    <!-- shiro全局异常 -->
//    org.apache.shiro.ShiroException
    
    @RequestMapping(value = "/login")
    public String showLoginForm(HttpServletRequest req, Model model) {
        String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
        String error = null;
        if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名不存在";
        } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名或者密码错误";
        }else if(LockedAccountException.class.getName().equals(exceptionClassName)) {
        	//用户被锁定，例如管理员把某个用户禁用...  
            error = "密码错误次数过多,账号被锁定10分钟,稍后再试.";
        } else if (ConcurrentAccessException.class.getName().equals(exceptionClassName)) {
            //登录异常
            error = "用户名错误";
        } else if (AuthenticationException.class.getName().equals(exceptionClassName)) {
            error = "用户名或者密码错误";
        } else if (exceptionClassName != null) {
            error = "验证码错误";
            log.warn(exceptionClassName);
        }
        model.addAttribute("error", error);
        OprInfo oprInfo = (OprInfo) SecurityUtils.getSubject().getPrincipal();
        if (error == null && oprInfo != null) {
            return "redirect:/";
        }
        return "login";
    }

    @RequestMapping(value = "/login/info")
    @ResponseBody
    public Map<String, Object> loginInfo() {
        OprInfo oprInfo = (OprInfo) SecurityUtils.getSubject().getPrincipal();
        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("loginId", oprInfo.getLoginId());
        retMap.put("oprName", oprInfo.getOprName());
        retMap.put("phone", oprInfo.getPhone());
        retMap.put("email", oprInfo.getEmail());
        String lastdt = (String) oprInfo.getLastDt();
        String lasttm = (String) oprInfo.getLastTm();
        if (StringUtils.isNotEmpty(lastdt) && StringUtils.isNotEmpty(lasttm)) {
            retMap.put("lastDtTm", DateUtils.transferDtTm((String) oprInfo.getLastDt() + (String) oprInfo.getLastTm()));
        }
        return retMap;
    }

    @RequestMapping("/exit")
    public ModelAndView exit(HttpServletRequest request, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            if (subject.getSession() != null && subject.getPrincipal() != null) {
                //退出销毁
                SecurityUtils.getSubject().logout();
                return new ModelAndView("redirect:/login");
            }
        }
        return new ModelAndView("redirect:/");
    }
}
